<template>
  <div>
    <!-- 三级分类组件 -->
    <Category :scene="scene" />

    <!-- 卡片内容展示 -->
    <el-card class="spu_el_card">
      <div v-show="scene === 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!categoryStore.category3Id"
          @click="addSpu"
        >
          添加SPU
        </el-button>
        <el-table
          class="spu_el_table"
          border
          stripe
          :data="records"
          v-if="records.length > 0"
        >
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="100"
          />
          <el-table-column
            align="center"
            label="SPU名称"
            prop="spuName"
            width="250"
          ></el-table-column>
          <el-table-column
            align="center"
            label="SPU描述"
            prop="description"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" label="操作" width="300">
            <template #default="{ row }">
              <el-button
                type="success"
                icon="Plus"
                size="small"
                title="添加SKU"
                @click="addSku(row)"
              />
              <el-button
                type="warning"
                icon="Edit"
                size="small"
                title="修改SPU"
                @click="updateSpu(row)"
              />
              <el-button
                type="info"
                icon="View"
                size="small"
                title="查看SKU列表"
                @click="showSkuList(row)"
              />
              <el-popconfirm
                :title="`确定要删除${row.spuName}这个SPU吗？`"
                width="250px"
                @confirm="deleteSpu(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    title="删除SPU"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else />
        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :size="'default'"
          :disabled="!(records.length > 0)"
          :background="true"
          layout="prev, pager, next, jumper, ->, total, sizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 添加SPU | 修改SPU 子组件 -->
      <SpuForm ref="spu" v-show="scene === 1" @changeScene="changeScene" />
      <!-- 添加SKU 子组件 -->
      <SkuForm ref="sku" v-show="scene === 2" @changeScene="changeScene" />
      <!-- dialog组件，展示SPU对应的SKU信息 -->
      <el-dialog v-model="dialogVisible" title="SKU列表">
        <el-table border stripe :data="skuArr">
          <el-table-column align="center" label="SKU名字" prop="skuName" />
          <el-table-column align="center" label="SKU价格" prop="price" />
          <el-table-column align="center" label="SKU重量" prop="weight" />
          <el-table-column align="center" label="SKU图片">
            <template #default="{ row }">
              <el-image
                :src="row.skuDefaultImg"
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
// 引入子组件
import SpuForm from '@/views/product/spu/spuForm.vue'
import SkuForm from '@/views/product/spu/skuForm.vue'
// 引入分类相关的仓库
import useCategoryStore from '@/store/modules/category'
// 引入接口
import { reqSpuList, reqDeleteSpu, reqGetSkuList } from '@/api/product/spu'
// 引入数据类型
import type {
  SpuData,
  SpuDataResponseData,
  Records,
  SkuDataResponseData,
  SkuData,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'

// 获取三级分类仓库
const categoryStore = useCategoryStore()

// 定义场景的数组，控制三级分类组件是否禁用 【结构切换：0：显示已有的SPU列表；1：添加或修改已有的SPU；2：添加新的SKU】
let scene = ref<number>(0)
// 定义当前页码
let currentPage = ref<number>(1)
// 定义每页记录数
let pageSize = ref<number>(5)
// 定义数据总数
let total = ref<number>(0)
// 存储 SPU 列表数据
let records = ref<Records>([])
// 获取子组件实例 SpuForm
let spu = ref<any>()
// 获取子组件实例 SkuForm
let sku = ref<any>()
// 存储全部的 SKU 列表的数据
let skuArr = ref<SkuData[]>([])
// 控制 dialog 组件的显示与隐藏
let dialogVisible = ref<boolean>(false)

// 监听三级分类的变化
watch(
  () => categoryStore.category3Id,
  () => {
    // 务必保证要有三级分类的 id
    if (!categoryStore.category3Id) return
    // 发请求获取spu列表数据
    getSpuList()
  },
)

// 获取 SPU 列表数据
const getSpuList = async (page = 1) => {
  currentPage.value = page
  let result: SpuDataResponseData = await reqSpuList(
    currentPage.value,
    pageSize.value,
    categoryStore.category3Id,
  )
  if (result.code === 200) {
    records.value = result.data.records
    total.value = result.data.total
  }
}

// 添加 SKU 按钮点击的回调
const addSku = (row: SpuData) => {
  scene.value = 2
  // 调用子组件的方法，初始化 添加sku的数据
  sku.value.initSkuData(
    categoryStore.category1Id,
    categoryStore.category2Id,
    row,
  )
}

// 添加 SPU 按钮点击的回调
const addSpu = () => {
  // 切换场景为 1，展示添加或修改已有 SPU 的表单
  scene.value = 1
  // 点击添加按钮，调用子组件的方法，初始化数据
  spu.value.initAddSpuData(categoryStore.category3Id)
}

// 修改 SPU 按钮点击的回调
const updateSpu = (row: SpuData) => {
  // 切换场景为 1，展示添加或修改已有 SPU 的表单
  scene.value = 1
  // 调用子组件 spuForm 的方法，将当前点击的 row 传递给子组件，让子组件展示修改的表单
  spu.value.initHasSpuData(row)
}

// 查看 SKU 列表按钮点击的回调
const showSkuList = async (row: SpuData) => {
  let result: SkuDataResponseData = await reqGetSkuList(row.id as number)
  if (result.code === 200) {
    skuArr.value = result.data
    dialogVisible.value = true
  }
}

// 删除 SPU 按钮点击的回调
const deleteSpu = async (row: SpuData) => {
  let result = await reqDeleteSpu(row.id as number)
  if (result.code === 200) {
    ElMessage.success('删除SPU成功')
  } else {
    ElMessage.error('删除SPU失败')
  }
  await getSpuList(
    records.value.length > 1 ? currentPage.value : currentPage.value - 1,
  )
}

// 子组件 spuForm 绑定的自定义事件：目前是让子组件通知父组件切换场景为 0
const changeScene = (Obj: any) => {
  // 子组件 spuForm 点击取消按钮，切换场景为 0，展示已有的 SPU 列表数据
  scene.value = Obj.flag
  // 再次请求数据获取全部的 SPU ，刷新数据
  if (Obj.params === 'update') {
    getSpuList(currentPage.value)
  } else {
    getSpuList()
  }
}

// 每页记录数改变时触发的回调
const handleSizeChange = () => {
  getSpuList()
}

// 当前页码改变时触发的回调
const handleCurrentChange = (val: number) => {
  getSpuList(val)
}

// 当路由组件销毁的时候，把仓库中三级分类相关的数据清空
onBeforeUnmount(() => {
  // 清空分类仓库中的数据
  categoryStore.$reset()
})
</script>

<style scoped>
.spu_el_card {
  margin: 10px 0;
}
.spu_el_table {
  margin: 20px 0;
}
</style>
